package com.bootlever.framework.fastdfs.aop;

import com.bootlever.framework.common.utils.FileUtils;
import com.bootlever.framework.common.utils.StringUtils;
import com.bootlever.framework.fastdfs.properties.FastdfsProperties;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class FileFilter {

    private static final Logger logger = LoggerFactory.getLogger(FileFilter.class);

    @Autowired
    private FastdfsProperties fastdfsProperties;

    @Pointcut("execution(* com.bootlever.framework.fastdfs.templates.FastdfsTemplate.upload*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object execute(ProceedingJoinPoint joinPoint) throws Throwable {
        if (logger.isInfoEnabled()){
            logger.info("进入Fasfdfs上传拦截...");
        }
        if (StringUtils.isBlank(fastdfsProperties.getExclude())){
            return joinPoint.proceed();
        }
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg != null){
                String extName = FileUtils.getFileExt(arg.toString());
                if (StringUtils.isNotBlank(extName) && fastdfsProperties.getExclude().contains(extName)){
                    logger.error("文件后缀名被过滤，无法上传:{}", extName);
                    return null;
                }
            }
        }
        return joinPoint.proceed();
    }
}
